a7d79c4e3f4a407ee937749b3fc1db29 by 2025

a7d79c4e3f4a407ee937749b3fc1db29 by 2025

Author:2025
Language: eng
Format: epub


Chapter 4 Unit test .net appliCations

Figure 4-1. The datatable.json file Build Action and Copy to Output Directory directives

We need now to write a little helper in C#, named EmbeddedJsonFileHelper, based on Newtonsoft.Json to read the file and fill a DataTable as shown in Listing 4-7.

Listing 4-7. The EmbeddedJsonFileHelper class

using Newtonsoft.Json;

namespace Apress.UnitTests.DataTables.Helpers;

public static class EmbeddedJsonFileHelper

{

public static T GetContent<T>(string filename)

{

return JsonConvert.DeserializeObject<T>(File.ReadAll

Text($"{filename}.json"));

}

}

82

Chapter 4 Unit test .net appliCations

We are ready to write our unit test! Listing 4-8 shows the Order ServiceTests test class with its test method named GetAsync_WhenGet AsyncRepositoryMethodReturnAFilledDataTable_GetAsyncServiceMethod ReturnsAListOfTransactions.

Listing 4-8. The OrderServiceTests class

using Apress.UnitTests.DataTables;

using Apress.UnitTests.DataTables.Helpers;

using ExpectedObjects;

using NSubstitute;

using System.Data;

using Xunit;

namespace Apress.UnitTests;

public class OrderServiceTests

{

[Fact]

public async Task GetAsync_WhenGetAsyncRepository

MethodReturnAFilledDataTable_GetAsyncServiceMethod

ReturnsAListOfTransactions()

{

// Arrange

IOrderRepository orderRepositoryMock = Substitute.

For<IOrderRepository>();

DataTable table = new DataTable();

table.Columns.Add("Id", typeof(long));

table.Columns.Add("Quantity", typeof(int));

table.Columns.Add("Date", typeof(DateTime));

var datatable = EmbeddedJsonFileHelper.GetContent

<DataTable>(@"DataTables\datatable");

foreach (DataRow row in datatable.Rows)

83

Chapter 4 Unit test .net appliCations

{

table.ImportRow(row);

}

orderRepositoryMock.GetAsync().Returns(x => table);

var expectedResult = new List<Order>

{

new Order { Id = 1, Quantity = 10, Date = DateTime.

Parse("2025-01-20") },

new Order { Id = 2, Quantity = 20, Date = DateTime.

Parse("2025-02-12")},

new Order { Id = 3, Quantity = 30, Date = DateTime.

Parse("2025-02-02")}

}.ToExpectedObject();

// Act

var service = new OrderService(orderRepositoryMock);

var result = await service.GetAsync();

// Assert

expectedResult.ShouldEqual(result);

}

}

As you can see, I have reused the libraries I introduced in the previous chapter. Additionally, using JSON to mock a DataTable greatly improved the test efficiency and readability! However, I had to create a DataTable manually with only the columns. Why? When using Newtonsoft.Json to deserialize JSON into a DataTable, integer numbers are often converted into long instead of int. This behavior occurs because Newtonsoft.Json uses the most inclusive numeric type (long) by default to avoid data loss from large numbers. Same for decimal, it’s using doubles instead of 84



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(58611)
What's Done in Darkness by Kayla Perrin(26846)
The Ultimate Python Exercise Book: 700 Practical Exercises for Beginners with Quiz Questions by Copy(20721)
De Souza H. Master the Age of Artificial Intelligences. The Basic Guide...2024 by Unknown(20484)
D:\Jan\FTP\HOL\Work\Alien Breed - Tower Assault CD32 Alien Breed II - The Horror Continues Manual 1.jpg by PDFCreator(20470)
The Fifty Shades Trilogy & Grey by E L James(19367)
Shot Through the Heart: DI Grace Fisher 2 by Isabelle Grey(19295)
Shot Through the Heart by Mercy Celeste(19150)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 10 by Isuna Hasekura and Jyuu Ayakura(17319)
Python GUI Applications using PyQt5 : The hands-on guide to build apps with Python by Verdugo Leire(17256)
Peren F. Statistics for Business and Economics...Essential Formulas 3ed 2025 by Unknown(17104)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 03 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(17025)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 01 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(16640)
The Subtle Art of Not Giving a F*ck by Mark Manson(14651)
The 3rd Cycle of the Betrayed Series Collection: Extremely Controversial Historical Thrillers (Betrayed Series Boxed set) by McCray Carolyn(14339)
Stepbrother Stories 2 - 21 Taboo Story Collection (Brother Sister Stepbrother Stepsister Taboo Pseudo Incest Family Virgin Creampie Pregnant Forced Pregnancy Breeding) by Roxi Harding(14029)
Scorched Earth by Nick Kyme(12995)
Drei Generationen auf dem Jakobsweg by Stein Pia(11180)
Suna by Ziefle Pia(11110)
Scythe by Neal Shusterman(10595)